using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Material.Mvc.Services;

namespace OpenAi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OpenAIController : ControllerBase
    {
        private readonly ICustomerService _customerService;

        public OpenAIController(ICustomerService customerService)
        {
            _customerService = customerService;
        }

        /// <summary>
        /// 处理用户发送的消息并获取智能客服的回复
        /// </summary>
        /// <param name="userId">用户唯一标识符，用于维护对话上下文</param>
        /// <param name="message">用户发送的具体消息内容</param>
        /// <returns>返回包含客服回复内容的JSON对象</returns>
        [HttpGet]
        public async Task<IActionResult> Chat([FromQuery] string userId, [FromQuery] string message)
        {
            if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(message))
            {
                return BadRequest("UserId and message are required");
            }

            try
            {
                var response = await _customerService.ProcessMessageAsync(userId, message);
                return Ok(new { response });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = ex.Message });
            }
        }

        /// <summary>
        /// 清除指定用户的所有对话历史记录
        /// </summary>
        /// <param name="userId">需要清除对话历史的用户唯一标识符</param>
        /// <returns>返回操作是否成功的结果</returns>
        [HttpPost]
        public async Task<IActionResult> ClearHistory([FromQuery] string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return BadRequest("UserId is required");
            }

            try
            {
                var result = await _customerService.ClearHistoryAsync(userId);
                return Ok(new { success = result });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = ex.Message });
            }
        }

        /// <summary>
        /// 初始化智能客服的知识库系统   
        /// </summary>
        /// <returns>返回知识库初始化是否成功的结果</returns>
        [HttpPost]
        public async Task<IActionResult> InitializeKnowledgeBase()
        {
            try
            {
                var result = await _customerService.InitializeKnowledgeBaseAsync();
                return Ok(new { success = result });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = ex.Message });
            }
        }

        [HttpGet]
        public async Task<IActionResult> TestConnection()
        {
            try
            {
                var result = await _customerService.TestConnectionAsync();
                return Ok(new { result });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = ex.Message });
            }
        }

    }
}
